﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Adams.Web.Data.Events
{
    public static class Index
    {
        public static Adams.Web.Models.Events.Index.PageLoad PageLoad()
        {
            var data = new Adams.Web.Models.Events.Index.PageLoad() { 
                Calendars = new Shared.Entities.Events.CalendarCollection()
            };

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT *
FROM Events.Calendars
", CommandType.Text))
            {
                while (dr.Read())
                {
                    var calendar = DB.InitFromReader<Shared.Entities.Events.Calendar>(dr, new ColMap { NameInDb = "CalendarID", NameInObject = "ID" });
                    data.Calendars.Add(calendar);
                }
            }

            return data;
        }

        public static Adams.Web.Models.Events.EventCollection GetEvents(DateTime start, DateTime end)
        {
            var data = new Adams.Web.Models.Events.EventCollection();

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT O.* , C.Color
FROM Events.Occurances O
INNER JOIN Events.Events E ON O.EventID = E.EventID
INNER JOIN Events.Calendars C ON C.CalendarID = E.CalendarID
WHERE DATEDIFF(d, @StartDate, O.StartDate) >= 0 AND DATEDIFF(d, O.StartDate, @EndDate) >= 0
", CommandType.Text,
    DB.CreateParameter("@StartDate", start),
    DB.CreateParameter("@EndDate", end)))
            {
                while (dr.Read())
                {
                    var e = new Adams.Web.Models.Events.Event();
                    e.id = dr["OccuranceID"].DbInt();
                    e.eventid = dr["EventID"].DbInt();
                    e.title = dr["Title"].DbString();
                    e.start = dr["StartDate"].DbDate().ToString();
                    e.end = dr["EndDate"].DbDate().ToString();
                    e.allDay = dr["IsAllDay"].DbBool();
                    e.color = dr["Color"].DbString();
                    data.Add(e);
                }
            }

            return data;
        }
    }
}